﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.Security.Cryptography;



namespace MapEditorMario
{

    public partial class ViewMap : Form
    {

        bool at = true;
        bool drawTile = false;
        int xTam = 0;
        int yTam = 0;
        string nameFileTemp = "";
        PictureBox picture = new PictureBox();
        int widthTempMap = 0;
        int x_door;
        int y_door;
        int nodeSize = 4096;
        int x_Pic; 
        int y_Pic;
        int idChoice = 0;//Choice
        List<ObjectMap> listObject = new List<ObjectMap>();
        List<ObjectTemp> urlImage = new List<ObjectTemp>();
        List<ObjAreaMove> areaMove = new List<ObjAreaMove>();
        List<ObjectMap> listTiles = new List<ObjectMap>();

        //array quan ly matran tiles
        int[,] array;// = new int[16, 48];
        List<Bitmap> list = new List<Bitmap>();
        
        int countCell_Height;
        int countCell_Width;
        public static String fileName = "";


        Point startDrag;

        Stream streamFile;
        QuadTree qTree;

        public ViewMap()
        {
            InitializeComponent();
            //vScrollBar.Maximum = nodeSize - 600 + 10;
            //qTree = new QuadTree(0, 0, nodeSize, 5);
            label_coordinate.Text = "0, " + (nodeSize - y_door - 599).ToString();

            String[] item = {"None","Scene 1", "Scene 2", "Scene 3"};
            coBox_Scene.DataSource = item;
        }

        private void ViewMap_Load(object sender, EventArgs e)
        {
            listObject.Clear();
            //loadImage();
        }

        public struct IconInfo
        {
            public bool fIcon;
            public int xHotspot;
            public int yHotspot;
            public IntPtr hbmMask;
            public IntPtr hbmColor;
        }

        [DllImport("user32.dll")]
        public static extern IntPtr CreateIconIndirect(ref IconInfo icon);
        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);

        //Create Cursor flowing image of picturebox
        public static Cursor CreateCursor(Bitmap bmp, int xHotSpot, int yHotSpot)
        {
            IntPtr ptr = bmp.GetHicon();
            IconInfo tmp = new IconInfo();
            GetIconInfo(ptr, ref tmp);
            tmp.xHotspot = xHotSpot;
            tmp.yHotspot = yHotSpot;
            tmp.fIcon = false;
            ptr = CreateIconIndirect(ref tmp);
            return new Cursor(ptr);
        }

        //Load image in resource to add flowlayoutPanel
        private void loadImage(string[] fileName)
        {
            //string[] fileName = Directory.GetFiles("Resource");
            layoutPanel.Controls.Clear();
            //int idObject = 1;
            foreach (string nameImage in fileName)
            {
                PictureBox pic = new PictureBox();
                //pic.Name = nameImage;// (idObject).ToString();
                string path = nameImage.Split('\\')[1];
                string pa = path.Split('.')[0];
                pic.Name = pa;
                pic.SizeMode = PictureBoxSizeMode.StretchImage;
                pic.Cursor = Cursors.Hand;
                pic.Image = Image.FromFile(nameImage);
                pic.Width = 30;
                pic.Height = 30;
                layoutPanel.Controls.Add(pic);
                pic.Click += new EventHandler(pic_Click);
                //idObject++;
            }
        }

        private void bt_loadtiles_Click(object sender, EventArgs e)
        {

            ListScene ls = new ListScene();
            ls.ShowDialog();
            if (ListScene.exit == false)
            {
                return;
            }

            list.Clear();
            PanelMap.Controls.Clear();
            PanelMap.Height = 0;

            if (ListScene.fileTxt.Equals(""))
                return;
            nameFileTemp = ListScene.nameFile;
            loadMatrix(ListScene.fileTxt);
            loadBitmapTile(ListScene.fileImage);
            PanelMap.Height = countCell_Height * 32;
            hScrollBar.Maximum = countCell_Width * 32 - 800 + 10;
            
            PanelMap.Refresh();
            coBox_EditTiles.Enabled = true;

        }

        public void loadBitmapTile(String file)
        {
            
            Bitmap bitmap = new Bitmap(file);
            widthTempMap = bitmap.Width;
            int w = bitmap.Width / 32;
            int h = bitmap.Height / 32;
            
            for (int i = 0; i < w;  i++)
            {
                for (int j = 0; j < h;  j++)
                {
                    Bitmap bm = cutPic(bitmap, i, j);
                    list.Add(bm);
                }
            }
            //MessageBox.Show(list.Count.ToString());
        }

        private Bitmap cutPic(Bitmap bitmap, int i, int j)
        {
            Rectangle rect = new Rectangle(i * 32, j * 32, 32, 32);

            Bitmap bmp = bitmap.Clone(rect, PixelFormat.DontCare);

            return bmp;
        }

        private void loadMatrix(String file)
        {

            //if (file.Equals(""))
            //    return;

            ArrayList arr = new ArrayList();
            int count = 0;

            using (StreamReader r = new StreamReader(file))
            {
                
                String str;
                String s = r.ReadLine();
                countCell_Width = Int32.Parse(SplitString(s, ' ')[0].ToString());
                countCell_Height = Int32.Parse(SplitString(s, ' ')[1].ToString());
                array = new int[countCell_Height, countCell_Width];
                str = r.ReadLine();
                //str = r.ReadLine();
                while (str != null && count <= countCell_Height)
                {
                    
                    arr.Clear();
                    arr = SplitString(str, ' ');
                    for (int i = 0; i < countCell_Width; i++)
                    {
                        array[count, i] = Int32.Parse(arr[i].ToString());
                    }
                    count++;
                    str = r.ReadLine();
                }
                
                
                //MessageBox.Show(s);
            }
        }
       

        #region ScrollBar
        private void vScrollBar_ValueChanged(object sender, EventArgs e)
        {
            //PanelMap.Location = new Point(PanelMap.Location.X,-vScrollBar.Value);
            //PanelMap.Height = vScrollBar.Value + 600;
            //y_door = vScrollBar.Value;
            //label_coordinate.Text = x_door.ToString() + ", " + (nodeSize - y_door - 599).ToString();
        }
        private void hScrollBar_ValueChanged(object sender, EventArgs e)
        {
            PanelMap.Location = new Point(-hScrollBar.Value, PanelMap.Location.Y);
            PanelMap.Width = hScrollBar.Value + 800;
            x_door = hScrollBar.Value;
            label_coordinate.Text = x_door.ToString() + ", " + (nodeSize - y_door - 599).ToString();
        }
        #endregion
        //Position x, y of Object when Mouse move
        private void MapPoint_MouseMove(object sender, MouseEventArgs e)
        {
            x_Pic = e.X;
            y_Pic = e.Y;
            //label_curX.Text = x_Pic.ToString();
            //label_curY.Text = (nodeSize - y_Pic).ToString();
        }

        
        //Paint Object on PanelMap
        private void PanelMap_Paint(object sender, PaintEventArgs e)
        {
            if (drawTile == false)
            if (list.Count > 0)

                for (int i = 0; i < countCell_Width; i++)
                {
                    for (int j = 0; j < countCell_Height; j++)
                    {
                        PictureBox p = new PictureBox();
                        p.Width = 32;
                        p.Height = 32;
                        p.Location = new Point(i * 32, j * 32);
                        p.Image = list[array[j, i]];
                        using (Pen pen = new Pen(Color.Red, 2))
                        {
                            e.Graphics.DrawImage(p.Image,
                            new Point(i * 32, j * 32));
                        }

                    }
                }
        }

           
        #region Click Picturebox and click on PanelMap
        public void pic_Click(object sender, EventArgs e)
        {
            picture = (PictureBox)sender;
            //ID.Text = picture.Name;
            PanelMap.Cursor = CreateCursor(new Bitmap(picture.Image), 0, 0);
            //idChoice = 1;
        }

        private void createNewObject(PictureBox pic, int posX, int posY)
        {
            
            PictureBox picbox = new PictureBox();
            
            if (pic.Image == null)
            {
                return;
            }
            picbox.Image = pic.Image;
            picbox.Name = pic.Name;
            picbox.Width = picbox.Image.Width;
            picbox.Height = picbox.Image.Height;
            picbox.Location = new Point(posX, posY);
            picbox.BackColor = Color.White;

            picbox.MouseClick += picbox_MouseClick;
            picbox.MouseDown += picbox_MouseDown;
            picbox.MouseMove += picbox_MouseMove;
            picbox.MouseUp += picbox_MouseUp;

            PanelMap.Controls.Add(picbox);
            ObjectMap obj = new ObjectMap(picbox);
            if (drawTile == true)
            {
                listTiles.Add(obj);
            }
            listObject.Add(obj);
        }

        private void picbox_MouseUp(object sender, MouseEventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            if (e.Button == MouseButtons.Left)
            {
                if (drawTile == false)
                    createNewObject(picture, e.X + pic.Left, e.Y + pic.Top);
            }
        }

        private void picbox_MouseMove(object sender, MouseEventArgs e)
        {
            //PictureBox pic = (PictureBox)sender;
            //pic.Location = new Point(e.X + pic.Left - startDrag.X, e.Y + pic.Top - startDrag.Y);
        }

        private void picbox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                startDrag = e.Location;
            }
        }

        private void picbox_MouseClick(object sender, MouseEventArgs e)
        {
            PictureBox pic = (PictureBox)sender;
            if (e.Button == MouseButtons.Right)
            {
                if (at == false)
                {
                    MessageBox.Show("Có Tiles còn trống");
                    return;
                }

                //If drawTile == true --> 
                if (drawTile == true)
                {
                    if (listTiles.Count > 0)
                    {
                        PanelMap.Cursor = Cursors.Hand;
                        listTiles.RemoveAt(PanelMap.Controls.GetChildIndex(pic));
                        at = false;
                        PanelMap.Controls.Remove(pic);
                    }
                }
                else
                {
                    if (listObject.Count > 0)
                    {
                        PanelMap.Cursor = Cursors.Hand;
                        listObject.RemoveAt(PanelMap.Controls.GetChildIndex(pic));
                        PanelMap.Controls.Remove(pic);
                    }
                }
            }
        }

        private void PanelMap_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {

                if (tbox_number.Equals("0"))
                {
                    createNewObject(picture, x_Pic, y_Pic);
                    return;
                }

                if (!tbox_number.Text.Equals(""))
                {
                    int number = Int32.Parse(tbox_number.Text.ToString());
                    for (int i = 0; i < number; i++)
                    {
                        createNewObject(picture, x_Pic, y_Pic);
                        x_Pic += 32;
                    }
                }

                if (chBox_shortLand.Checked == true)
                {
                    PictureBox b = new PictureBox();
                    b.Image = Image.FromFile("Resource/22.png");
                    for (int i = 0; i < 12; i++)
                    {
                        createNewObject(picture, x_Pic, y_Pic);
                        x_Pic += 32;
                    }
                }
                
                if(chBox_longLand.Checked == true){
                    int countLand = widthTempMap/32;
                    int startPo = 0;
                    PictureBox b = new PictureBox();
                    //b.Image = Image.FromFile("Resource/22.png");
                    for (int i = 0; i < countLand; i++)
                    {
                        createNewObject(picture, startPo, y_Pic);
                        startPo += 32;
                    }
                }


                if (drawTile == true)
                {
                    xTam = e.X / 32;
                    yTam = e.Y / 32;
                    createNewObject(picture, xTam * 32, yTam * 32);
                    at = true;
                    array[yTam, xTam] = Int32.Parse(picture.Name.ToString());
                }
                else
                    createNewObject(picture, e.X, e.Y);
            }
            
        }

        private void button_autoLand_Click(object sender, EventArgs e)
        {
            idChoice = 3;
            PanelMap.Cursor = CreateCursor(new Bitmap(Image.FromFile("Resource/22.png")), 0, 0);
        }
        #endregion

        #region Save and Open Map

        //translate position on MapView to Map Game
        public void mapPos_GamePos()
        {

            for (int i = 0; i < listObject.Count; i++)
            {
                listObject[i].y = 4096 - listObject[i].y - listObject[i].height / 2;
                listObject[i].x = listObject[i].x + listObject[i].width / 2;
            }
        }

        //save map to file
        public void saveFileMap()
        {
            //mapPos_GamePos();
            using (StreamWriter w = new StreamWriter(streamFile))
            {
                //w,h, num diem, mang, num coin, posx fisrt, posy fist, posx last, posy last, obj_state, direction
                //w.WriteLine(8 + " " + listObject.Count.ToString() + " " + "0 0 0 128 292 4768 227 2 0");

                //Set position for simon
                int pos_x_first = 128, pos_y_first = 292;
                for (int i = 0; i < listObject.Count; i++)
                {
                    int obj_type = Int32.Parse(listObject[i].id);
                    switch (obj_type)
                    {
                        case 1:
                            pos_x_first = listObject[i].x;
                            pos_y_first = PanelMap.Height - listObject[i].y;
                            break;
                    }
                }

                //Row 1 in map
                w.WriteLine(8 + " " + (listObject.Count - 1).ToString() + " " + "0 0 0 " + pos_x_first + " " + pos_y_first + " 4768 227 2 0");

                //Set position for others object
                for (int i = 0; i < listObject.Count; i++)
                {
                    int obj_type = Int32.Parse(listObject[i].id);
                    switch (obj_type)
                    {
                        case 11:
                            // id pos_x pos_y pos_x1 pos_y1 direction id_type 
                            w.WriteLine((i + 1) + " " + 2 + " "
                                + (listObject[i].x).ToString() + " "
                                + (PanelMap.Height - listObject[i].y).ToString() + " "
                                + ((listObject[i].x) + listObject[i].width) + " "
                                + (((PanelMap.Height - listObject[i].y)) - listObject[i].height) + " "
                                + listObject[i].direction.ToString() + " "
                                + listObject[i].id.ToString());
                            break;
                        case 12:

                            break;
                        case 22:
                            // id pos_x pos_y pos_x1 pos_y1 direction id_type 
                            w.WriteLine((i + 1) + " " + listObject[i].status.ToString() + " "
                                + (listObject[i].x).ToString() + " "
                                + (PanelMap.Height - listObject[i].y).ToString() + " "
                                + ((listObject[i].x) + listObject[i].width) + " "
                                + (((PanelMap.Height - listObject[i].y)) - listObject[i].height) + " "
                                + listObject[i].direction.ToString() + " "
                                + listObject[i].id.ToString());
                            break;

                        default:
                            // id pos_x pos_y pos_x1 pos_y1 direction id_type 
                            if (obj_type != 1)
                            {
                                w.WriteLine((i + 1) + " " + listObject[i].status.ToString() + " "
                                    + (listObject[i].x).ToString() + " "
                                    + (PanelMap.Height - listObject[i].y).ToString() + " "
                                    + ((listObject[i].x) + listObject[i].width) + " "
                                    + (((PanelMap.Height - listObject[i].y)) - listObject[i].height) + " "
                                    + listObject[i].direction.ToString() + " "
                                    + listObject[i].id.ToString());
                            }
                            break;
                    }

                    
                }
            }
        }

        public void openFileMap()
        {
            listObject.Clear();
            listObject = new List<ObjectMap>();
            this.Refresh();
            imageName();
            using (StreamReader r = new StreamReader(streamFile))
            {
                ArrayList listTemp = new ArrayList();

                string strOb;

                //cho nay sao doc 3 lan lan
                //do luc truoc tao cho dong dau la so luong
                //dong 2 de trong
                strOb = r.ReadLine();
                //strOb = r.ReadLine();
                strOb = r.ReadLine();
                while (strOb != null)
                {
                    if (strOb == null)
                    {
                        break;
                    }

                    listTemp = SplitString(strOb, ' ');

                    for (int i = 0; i < urlImage.Count; i++ )
                    {
                        //gio k biet no load cho nao luon
                        //cai cho nay bang 1 dung khong
                        //may chon sai file rui ha j do??

                        if ((urlImage[i].id).Equals(listTemp[7].ToString()))
                        {
                            PictureBox pic = new PictureBox();
                            pic.Name = urlImage[i].id;
                            pic.Image = Image.FromFile(urlImage[i].url);
                            pic.Width = pic.Image.Width;
                            pic.Height = pic.Image.Height;
                            pic.Location = new Point(Convert.ToInt32(listTemp[2].ToString())    // - urlImage[i].width/2
                                , PanelMap.Height - Convert.ToInt32(listTemp[3].ToString()));
                            ObjectMap newOb = new ObjectMap(pic);
                            //PanelMap.Controls.Add(pic);
                            createNewObject(pic, Convert.ToInt32(listTemp[2].ToString())        // - urlImage[i].width/2
                                ,PanelMap.Height - Convert.ToInt32(listTemp[3].ToString()));
                         //   listObject.Add(newOb);
                        }
                    }
                    
                    strOb = r.ReadLine();
                }
            }
            this.Refresh();
        }

        private void button_saveMap_Click(object sender, EventArgs e)
        {
            saveFile.Filter = "Map Files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFile.InitialDirectory = Application.StartupPath + @"\Map";
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                if ((streamFile = saveFile.OpenFile()) != null)
                {
                    saveFileMap();
                    streamFile.Close();
                }

                string file_name = saveFile.FileName;
                
                MessageBox.Show(file_name);


                string file_name_temp = file_name.Replace(".txt", "-qt.txt");

                //Xu ly lay size quadtree
                int temp_size = countCell_Width * 32;
                qTree = new QuadTree(0, 0, temp_size, 5);

                qTree.addAllCTreeObject(file_name);
                qTree.divide();
                //qTree.saveQTree(file_name + "-qt.txt");
                qTree.saveQTree(file_name_temp);

                MessageBox.Show("Save Complete!" + qTree.sum_node);
            }
        }

        private void button_openMap_Click(object sender, EventArgs e)
        {
            openFile.Filter = "Map Files (*.txt)|*.txt|All files (*.*)|*.*";
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                if ((streamFile = openFile.OpenFile()) != null)
                {
                    openFileMap();
                    streamFile.Close();
                }
            }
            this.Refresh();
        }

        public ArrayList SplitString(string str, char ch)
        {
            ArrayList list = new ArrayList();
            int n = str.Length;
            string line = "";
            for (int i = 0; i < n; i++)
            {
                while ((i < n) && (String.Compare(str[i].ToString(), ch.ToString()) != 0))
                {
                    line += str[i];
                    i++;
                }
                list.Add(line);
                line = "";
            }
            return list;
        }

        public void imageName()
        {
            string[] fileName = Directory.GetFiles("Resource");
            int idCount = 1;
            string id;
            string url;
            int width, height;

            //ua cho nay nhu the nay  lam sao load duoc
            //may cho id = ten cua tam hinh ha? uh thi ki truoc tao cho id cua tam hinh ma
            //may lam sao lay dc ten cua tam hinh, theo 11, 22, ....
            // tao co lam roi

            foreach (string nameImage in fileName)
            {
                string path = nameImage.Split('\\')[1];
                string pa = path.Split('.')[0];
                id = pa;
                url = nameImage;
                width = Image.FromFile(nameImage).Width;
                height = Image.FromFile(nameImage).Height;
                ObjectTemp newOb = new ObjectTemp(url, id, width, height);
                urlImage.Add(newOb);
                idCount++;
            }
        }

        //New map
        private void button_newMap_Click(object sender, EventArgs e)
        {
            listObject.Clear();
            PanelMap.Controls.Clear();
            this.Refresh();
        }
        #endregion

        private void bt_cuttiles_Click(object sender, EventArgs e)
        {
            EditPicture formTiles = new EditPicture();
            formTiles.ShowDialog();
        }

        private void bt_longLand_Click(object sender, EventArgs e)
        {
            idChoice = 4;
            PanelMap.Cursor = CreateCursor(new Bitmap(Image.FromFile("Resource/22.png")), 0, 0);
        }

        public void showLayout()
        {
            for (int i = 0; i < list.Count; i++)
            {
                PictureBox pic = new PictureBox();
                pic.Name = (i).ToString();
                pic.SizeMode = PictureBoxSizeMode.StretchImage;
                pic.Cursor = Cursors.Hand;
                pic.Image = list[i];
                pic.Width = 30;
                pic.Height = 30;
                layoutPanel.Controls.Add(pic);
                pic.Click += new EventHandler(pic_Click);
            }
        }

        private void bt_editBg_Click(object sender, EventArgs e)
        {
            //layoutPanel.Controls.Clear();
            //showLayout();
            //PanelMap.Controls.Clear();
            //draw = true;
            //PanelMap.Refresh();
            //for (int i = 0; i < countCell_Width; i++)
            //{
            //    for (int j = 0; j < countCell_Height; j++)
            //    {
            //        PictureBox p = new PictureBox();
            //        p.Width = 32;
            //        p.Height = 32;
            //        p.Location = new Point(i * 32, j * 32);
            //        p.Image = list[array[j, i]];

            //        p.MouseClick += picbox_MouseClick;
            //        p.MouseDown += picbox_MouseDown;
            //        p.MouseMove += picbox_MouseMove;
            //        p.MouseUp += picbox_MouseUp;

            //        PanelMap.Controls.Add(p);
            //        ObjectMap obj = new ObjectMap(p);
            //        listObject.Add(obj);
            //    }
            //}
        }

        private void SaveMatrix(String file_name, int[] matrix)
        {

            if (listTiles.Count <= 0)
            {
                return;
            }
            FileStream fs = new FileStream(file_name, FileMode.Create); //tao file moi
            StreamWriter sWriter = new StreamWriter(fs); //

            sWriter.WriteLine(countCell_Width + " " + countCell_Height);

            int countWidth = 0;
            for (int i = 0; i < matrix.Length; i++)
            {
                sWriter.Write(matrix[i]);
                countWidth++;
                if (countWidth == countCell_Width)
                {
                    sWriter.WriteLine();
                    countWidth = 0;
                }
                else
                    sWriter.Write(" ");
            }

            sWriter.Flush();
            fs.Close();
        }

        private void bt_saveTile_Click(object sender, EventArgs e)
        {
            //int[] matrix = new int[listTiles.Count];
            //int countMatrix = 0;
            //for (int i = 0; i < countCell_Height; i++)
            //    for (int j = 0; j < countCell_Width; j++)
            //    {
            //        matrix[countMatrix] = array[i, j];
            //        countMatrix++;
            //    }
            //SaveMatrix("ResourceBackground/" + nameFileTemp, matrix);
        }

        private void coBox_EditTiles_CheckedChanged(object sender, EventArgs e)
        {

            if (at == false)
            {
                MessageBox.Show("Có tiles còn trống");
                coBox_EditTiles.Checked = true;
                return;
            }

            if (coBox_EditTiles.Checked)
            {
                layoutPanel.Controls.Clear();
                showLayout();
                PanelMap.Controls.Clear();
                drawTile = true;
                PanelMap.Refresh();
                for (int i = 0; i < countCell_Width; i++)
                {
                    for (int j = 0; j < countCell_Height; j++)
                    {
                        PictureBox p = new PictureBox();
                        p.Width = 32;
                        p.Height = 32;
                        p.Location = new Point(i * 32, j * 32);
                        p.Image = list[array[j, i]];

                        p.MouseClick += picbox_MouseClick;
                        p.MouseDown += picbox_MouseDown;
                        p.MouseMove += picbox_MouseMove;
                        p.MouseUp += picbox_MouseUp;

                        PanelMap.Controls.Add(p);
                        ObjectMap obj = new ObjectMap(p);
                        listTiles.Add(obj);
                    }
                }
                bt_loadtiles.Enabled = false;
                coBox_Scene.Enabled = false;
                //MessageBox.Show("true");
            }
            else
            {

                int size = (countCell_Width > countCell_Height) ? countCell_Width * 32 : countCell_Height * 32;
                QuadTree quadTree = new QuadTree(0, 0, size, 5);

                if (listTiles.Count <= 0)
                    return;
                drawTile = false;
                int[] matrix = new int[listTiles.Count]; 
                int countMatrix = 0;
                for (int i = 0; i < countCell_Height; i++)
                    for (int j = 0; j < countCell_Width; j++)
                    {
                        //bi loi j z
                        //ah cai nay do muc may de trong tiles

                        matrix[countMatrix] = array[i, j];
                        countMatrix++;
                    }
                String name = nameFileTemp.Substring(0, nameFileTemp.Length - 4);

                //save map
                SaveMatrix("MapEditor/" + nameFileTemp, matrix);
                SaveTilesObject("MapEditor/" + nameFileTemp.Substring(0, nameFileTemp.Length - 4) + "-obj.txt", matrix);

                //Save quadtree tiles bg, them doan code nay nua de luu vo quadtree
                quadTree.addAllTiles(Application.StartupPath + @"\MapEditor\" + nameFileTemp.Substring(0, nameFileTemp.Length - 4) + ".txt");
                quadTree.divide();
                quadTree.saveQTree("MapEditor/" +  nameFileTemp.Substring(0, nameFileTemp.Length - 4) + "-obj-qt.txt");
                MessageBox.Show("Save Tiles map thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //quadTree.addAllTiles("MapEditor/" + nameFileTemp);
                //quadTree.divide();
                //quadTree.saveQTree("MapEditor/" + nameFileTemp.Substring(0, nameFileTemp.Length - 4) + "-obj-qt.txt");
                //MessageBox.Show("Save Tiles thành công");
                //Cho nay luu sao no khong luu file -obj-qt.txt

                listTiles.Clear();
                list.Clear();
                PanelMap.Controls.Clear();
                PanelMap.Height = 0;

                loadMatrix(ListScene.fileTxt);
                loadBitmapTile(ListScene.fileImage);
                PanelMap.Height = countCell_Height * 32;
                hScrollBar.Maximum = countCell_Width * 32 - 800 + 10;

                layoutPanel.Controls.Clear();
                bt_loadtiles.Enabled = true;
                coBox_Scene.SelectedIndex = 0;
                coBox_Scene.Enabled = true;
                PanelMap.Refresh();
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void SaveTilesObject(String file_name, int[] matrix)
        {
            //FileStream fs = new FileStream(file_name, FileMode.Create); //tao file moi
            //StreamWriter sWriter = new StreamWriter(fs); //

            //sWriter.Write(6 + " " + countCell_Width * countCell_Height + "\n");

            //int countWidth = 0;
            //int countHeight = 0;
            //for (int i = 0; i < matrix.Length; i++)
            //{
            //    sWriter.Write((i + 1) + " ");
            //    sWriter.Write(matrix[i]);
            //    int pos_x = countWidth * 32;
            //    int pos_y = countHeight * 32;
            //    sWriter.Write(" " + pos_x);
            //    sWriter.Write(" " + pos_y);
            //    sWriter.Write(" " + (pos_x + 32));
            //    sWriter.Write(" " + (pos_y + 32));
            //    sWriter.Write("\n");

            //    countWidth++;
            //    if (countWidth == countCell_Width)
            //    {
            //        //sWriter.Write("\n");
            //        countWidth = 0;
            //        countHeight++;
            //    }

            //}

            //sWriter.Flush();
            //fs.Close();
            FileStream fs = new FileStream(file_name, FileMode.Create); //tao file moi
            StreamWriter sWriter = new StreamWriter(fs); //

            sWriter.Write(6 + " " + countCell_Width * countCell_Height + " " + countCell_Width * 32 + "\n");

            int countWidth = 0;
            int countHeight = 0;
            for (int i = 0; i < matrix.Length; i++)
            {
                sWriter.Write((i + 1) + " ");
                sWriter.Write(matrix[i]);
                int pos_x = countWidth * 32;
                int pos_y = countHeight * 32;
                sWriter.Write(" " + pos_x);
                sWriter.Write(" " + pos_y);
                sWriter.Write(" " + (pos_x + 32));
                sWriter.Write(" " + (pos_y + 32));
                sWriter.Write("\n");

                countWidth++;
                if (countWidth == countCell_Width)
                {
                    //sWriter.Write("\n");
                    countWidth = 0;
                    countHeight++;
                }

            }

            sWriter.Flush();
            fs.Close();
        }

        private void coBox_Scene_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (coBox_Scene.SelectedIndex == 0)
            {
                layoutPanel.Controls.Clear();
            }
            else if (coBox_Scene.SelectedIndex == 1)
            {
                loadImage(Directory.GetFiles("Resource/Scene1"));
            }
            else if (coBox_Scene.SelectedIndex == 2)
            {
                loadImage(Directory.GetFiles("Resource/Scene2"));
            }
            else if (coBox_Scene.SelectedIndex == 3)
            {
                loadImage(Directory.GetFiles("Resource/Scene3"));
            }
        }


    }
}
